package com.estar.assistsurvy.activity;

import java.util.List;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.entity.EsBankCardInfo;
import com.estar.assistsurvy.entity.RequestWalletChange;
import com.estar.assistsurvy.entity.RequestWithdraw;
import com.estar.assistsurvy.entity.ResponseBankCardInfo;
import com.estar.assistsurvy.entity.ResponseMsg;
import com.estar.assistsurvy.thread.BankInfoThread;
import com.estar.assistsurvy.thread.WithDrawThread;
import com.estar.assistsurvy.utils.ExitUtils;
import com.estar.assistsurvy.utils.MightypleUtil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WithdrawActivity extends BaseActivity implements OnClickListener{

	private LinearLayout returnBack;
	private TextView cardInfo,statistics;
	private EditText amount_edit;
	private Button withdraw_bt;
	private boolean canWithdraw=false;
	private int withdrawTimes;
	private Intent intent;
	private SharedPreferences prefer;
	private String uuid,deviceId,totalAmount,amount;
	private List<EsBankCardInfo> esBankCardInfoList;
	private EsBankCardInfo bankCard;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case -1:
				showShortToast((String) msg.obj);
				break;
				
			case 0:
				ResponseBankCardInfo bankCardInfo=new ResponseBankCardInfo();
				bankCardInfo=(ResponseBankCardInfo) msg.obj;
				if(bankCardInfo.getCode().equals("1")){
					esBankCardInfoList=bankCardInfo.getEsBankCardInfoList();
					if(esBankCardInfoList.size()>0){
						bankCard=esBankCardInfoList.get(esBankCardInfoList.size()-1);
						StringBuffer buffer=new StringBuffer();
						String cardName=bankCard.getBankTopclassName();
						String cardNumber=bankCard.getBankCardNumber();
						String cardNumberTemp=null;
						if(cardNumber.length()>4){
							cardNumberTemp=cardNumber.substring(cardNumber.length()-4,cardNumber.length());
						}else{
							cardNumberTemp=cardNumber;
						}
						buffer.append(cardName+"\t");
						buffer.append(cardNumberTemp);
						cardInfo.setText(buffer.toString());
						canWithdraw=true;
					}else{
						new AlertDialog.Builder(WithdrawActivity.this, AlertDialog.THEME_HOLO_LIGHT)
						.setMessage("当前账户未绑定银行卡，请前往绑定")
						.setCancelable(false)
						.setPositiveButton("前往", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								intent=new Intent(WithdrawActivity.this, AddBankCardActivity.class);
								startActivity(intent);
							}
						})
						.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
						.create()
						.show();
					}
				}else if(bankCardInfo.getCode().equals("0")){
					showShortToast(bankCardInfo.getMessages());
				}else if(bankCardInfo.getCode().equals("2")){
					ExitUtils.Unlogin(WithdrawActivity.this, bankCardInfo.getMessages());
				}
				break;
				
			case 1:
				ResponseMsg message=new ResponseMsg();
				message=(ResponseMsg) msg.obj;
				if(message.getCode().equals("1")){
					withdrawTimes--;
					prefer=getSharedPreferences("user", MODE_PRIVATE);
					Editor editor=prefer.edit();
					editor.putInt("withdrawTimes", withdrawTimes);
					editor.commit();
				}
				showShortToast(message.getMessages());
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_withdraw);
		init();
	}
	
	private void init(){
		returnBack=find(R.id.returnBack);
		returnBack.setOnClickListener(this);
		cardInfo=find(R.id.cardInfo);
		amount_edit=find(R.id.amount_edit);
		amount_edit.setFilters(new InputFilter[] { lengthfilter }); 
		intent=getIntent();
		totalAmount=intent.getStringExtra("amount");
		statistics=find(R.id.statistics);
		prefer=getSharedPreferences("withdraw", MODE_PRIVATE);
		withdrawTimes=prefer.getInt("withdrawTimes", 5);
		statistics.setText("单笔上线5万元，今日可提现"+withdrawTimes+"次，当前可用余额"+totalAmount+"元");
		statistics.setVisibility(View.GONE);
		withdraw_bt=find(R.id.withdraw_bt);
		withdraw_bt.setOnClickListener(this);
		prefer=getSharedPreferences("user", MODE_PRIVATE);
		uuid=prefer.getString("uuid", "");
		deviceId=MightypleUtil.getDeviceId(this);
		RequestWalletChange bankInfo=new RequestWalletChange(deviceId,uuid);
		new BankInfoThread(this, handler, bankInfo).start();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.returnBack:
			finish();
			break;
			
		case R.id.withdraw_bt:
			if(canWithdraw){
				amount=amount_edit.getText().toString().trim();
				if(Float.parseFloat(amount)<=50){
					showShortToast("金额需大于等于50元!");
					return;
				}
				if(Float.parseFloat(amount)<=Float.parseFloat(totalAmount)){
					RequestWithdraw requestWithdraw=new RequestWithdraw(deviceId, uuid, amount, bankCard.getId(), bankCard.getBankCardNumber(), bankCard.getBankTopclassName());
					new WithDrawThread(this, handler, requestWithdraw).start();
				}else{
					showShortToast("提现金额超限!");
				}
			
			}else{
				showShortToast("当前账户未绑定银行卡,无法提现!");
			}
			break;

		default:
			break;
		}
	}
	
	/** 输入框小数的位数*/
	private static final int DECIMAL_DIGITS = 1; 
	/**
	 *  设置小数位数控制   
	 */
    InputFilter lengthfilter = new InputFilter() {   
        public CharSequence filter(CharSequence source, int start, int end,   
                Spanned dest, int dstart, int dend) {   
            // 删除等特殊字符，直接返回   
            if ("".equals(source.toString())) {   
                return null;   
            }   
            String dValue = dest.toString();   
            String[] splitArray = dValue.split("//.");   
            if (splitArray.length > 1) {   
                String dotValue = splitArray[1];   
                int diff = dotValue.length() + 1 - DECIMAL_DIGITS;   
                if (diff > 0) {   
                    return source.subSequence(start, end - diff);   
                }   
            }   
            return null;   
        }   
    };  
}
